package com.ddsso.auth.web.repository.impl;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.ddsso.auth.web.repository.LogoutDao;
import com.ddsso.auth.web.util.SerializeUtil;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * @author zdd
 * @package com.ddsso.auth.web.repository.impl
 * @Time Created by zdd on 2016/11/7.
 * @description To-do
 */
@Component("logoutDao")
public class LogoutDaoImpl extends BaseDaoImpl<HashSet<String>> implements LogoutDao {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    /********************************
     * @description  下面为服务的辅助类
     **********************************/
    // 反向会话放在 nkv 的 key 的前缀. 和其他业务的 key 分开
    private String backwardSessionKeyPrefix = "session.customerid.";

    // 正向会话放在 nkv 的 key 的前缀. 和其他业务的 key 分开
    // 必须和 framework-web 中的 NkvSessionDao.sessionKeyPrefix 一致
    private String forwardSessionKeyPrefix = "sessionid.";
    private String md5(String sessionId) {
        return sessionId == null ? null : DigestUtils.md5Hex(sessionId);
    }
    private String getBackwardSessionKey(String customerId) {
        return backwardSessionKeyPrefix + customerId;
    }

    private String getForwardSessionKey(String sessionId) {
        return forwardSessionKeyPrefix + sessionId;
    }

    public void removeSessionCustomer(String customerId){
        if(StringUtils.isNotBlank(customerId)){
            this.remove(getBackwardSessionKey(customerId));
        }
    }


    public void invalidSession(String customerId, String excludedSessionId) {
        Set<String> sessionIdSet=this.fetch(getBackwardSessionKey(customerId), HashSet.class);
        if (sessionIdSet == null) {
            logger.info("backward session is empty");
            return;
        }
        for (Iterator<String> iterator = sessionIdSet.iterator(); iterator.hasNext();) {
            String sessionId = iterator.next();
            logger.info("remove invalid backward session:" + sessionId);
            if(this.get(getForwardSessionKey(sessionId))!=null){
                this.remove(getForwardSessionKey(sessionId));
            }
            iterator.remove();
        }
        this.remove(getBackwardSessionKey(customerId));
        logger.info(("invalidSession").toString());
    }
}
